<template>
  <div class="">
    <!-- app-container -->
    <div class="head">
      <el-form :model="queryParams" ref="queryForm" :rules="rules" :inline="true">
        <el-form-item label="卡查询：" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入ID/赚卡名称" clearable />
        </el-form-item>
        <el-form-item label="所属/使用门店：" prop="merchantIdList">
          <el-select v-model="queryParams.merchantIdList" filterable multiple placeholder="请选择" clearable
            style="width: 240px">
            <el-option v-for="dict in merchantList" :key="dict.id" :label="dict.value" :value="dict.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="上架状态：" prop="sellStatusList">
          <el-select v-model="queryParams.sellStatusList" filterable multiple placeholder="请选择" clearable
            style="width: 240px">
            <el-option v-for="dict in functionTypeList" :key="dict.id" :label="dict.value" :value="dict.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="售价：" prop="">
          <div class="inpNum">
            <el-form-item label="" prop="startPrice" label-width="0">
              <el-input v-model="queryParams.startPrice" placeholder="请输入" clearable />
            </el-form-item>
            <div class="gang"> - </div>
            <el-form-item label="" prop="endPrice" label-width="0">
              <el-input v-model="queryParams.endPrice" placeholder="请输入" clearable />
            </el-form-item>
          </div>
        </el-form-item>
        <el-form-item label="参与活动：" prop="activeList">
          <el-select v-model="queryParams.activeList" filterable multiple placeholder="请选择" clearable style="width: 240px"
            @change="changeActiveList">
            <el-option v-for="dict in activeList" :key="dict.id" :label="dict.value" :value="dict.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="最后修改时间：" prop="date">
          <el-date-picker v-model="queryParams.date" type="daterange" value-format="yyyy-MM-dd" size="small"
            range-separator="至" @change="getTime" start-placeholder="开始日期" end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="标签查询：" prop="">
          <el-select v-model="queryParams.tagIdList" filterable multiple placeholder="请选择" clearable style="width: 240px">
            <el-option v-for="dict in tagList" :key="dict.tagId" :label="dict.tagName" :value="dict.tagId" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery('queryForm')">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="listBox">
      <div class="main_top">
        <div class="lef">
          <div class="nav_list" v-for="(item, index) in typeList"
            :class="['list', currentNavtab == item.id ? 'active' : '']" :key="index" :value="item.id"
            @click="handleTab(item.id)">
            <span>{{ item.value }}</span><span v-if="index != 0">({{ item.num }})</span>
          </div>
        </div>

      </div>
      <div class="listBox_head">
        <el-button type="primary" @click="addClick">新建赚卡</el-button>
        <el-button type="primary" @click="handleConfig">批量配置运营活动</el-button>
        <!-- <el-button type="primary"  @click="handlesell(2)">批量上架</el-button>
        <el-button type="primary"  @click="handlesell(1)">批量下架</el-button> -->
        <el-button type="primary" @click="handlesell(true)">批量上下架</el-button>
        <el-button type="primary" @click="handleDecrease">增减虚拟销量</el-button>
        <el-button type="primary" @click="handleLabel">批量设置标签</el-button>
        <el-dropdown split-button type="primary" @command="handleCommand">
          导出
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="1">
              选中导出
              <!-- <export-excel-button title="消费后激励活动" type="2" action="/merchant/lucrative/equity/card/assistance/export" :params="ExportIncentive" /> -->
            </el-dropdown-item>
            <el-dropdown-item command="2">
              全部导出
              <!-- <export-excel-button title="消费后激励活动" type="2" action="/merchant/lucrative/equity/card/assistance/export" :params="ExportIncentive" /> -->
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-button class="ml10" type="primary" @click="downloadImages">打包下载图片</el-button>
      </div>
      <el-table v-loading="loading" :data="tabList" stripe border @selection-change="handleSelectionChange">

        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column label="序号" align="center" type="index" width="64px" />
        <el-table-column label="商品ID" align="center" prop="goodsId" :show-overflow-tooltip="true" />
        <el-table-column label="赚卡名称" align="center" prop="name" :show-overflow-tooltip="true" />
        <el-table-column label="所属/适用门店" align="center" prop="shopName" :show-overflow-tooltip="true" />
        <el-table-column label="售价" align="center" prop="price" :show-overflow-tooltip="true" />
        <el-table-column label="APP/小程序库存" align="center" prop="issueTotal" :show-overflow-tooltip="true" />
        <el-table-column label="抖音库存" align="center" prop="dyInventoryTotal" :show-overflow-tooltip="true" />
        <el-table-column label="视频号库存" align="center" prop="wxVideoInventory" width="100" :show-overflow-tooltip="true" />
        <el-table-column label="已售" align="center" prop="soldTotal" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="虚拟销量" align="center" prop="virtualSalesVolume"
          :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="展示销量" align="center" prop="showSoldTotal" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="参与活动" align="center" prop="joinActivity" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="标签" align="center" prop="tag" width="150px" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div class="tagBox">
              <span v-for="(item, index) in scope.row.tag" :key="index">{{ item }}<i
                  v-if="index != scope.row.tag.length - 1">、</i></span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="上架状态" align="center">
          <el-table-column prop="sellStatus" align="center" label="APP/小程序" width="100">
          </el-table-column>
          <el-table-column prop="douyinSellStatus" align="center" label="抖音小程序" width="100">
          </el-table-column>
          <el-table-column prop="weChatVideo" align="center" label="微信视频号" width="100">
          </el-table-column>
        </el-table-column>
        <el-table-column label="最后修改时间" align="center" prop="updateTime" :show-overflow-tooltip="true" width="150px">
        </el-table-column>
        <el-table-column label="修改人" align="center" prop="updateBy" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="reviseClick(scope.row)"
              v-if="scope.row.sellStatusValue == 1 || scope.row.sellStatusValue == 4 || scope.row.sellStatusValue == 5">修改</el-button>
            <el-button size="mini" type="text" @click="editClick(scope.row)"
              v-if="scope.row.sellStatusValue == 3">编辑</el-button>
            <el-button size="mini" type="text" @click="handlesell(false, scope.row)"  v-if="scope.row.sellStatusValue == 3 || scope.row.sellStatusValue == 2">上下架</el-button>
            <!-- <el-button size="mini" type="text" @click="editStatus(scope.row)"  v-if="scope.row.sellStatusValue == 3"
              >上架</el-button>
              <el-button size="mini" type="text" @click="editStatus(scope.row)"  v-if="scope.row.sellStatusValue == 2 "
              >下架</el-button> -->
            <el-button size="mini" type="text" @click="lookClick(scope.row)"
              v-if="scope.row.sellStatusValue == 2 || scope.row.sellStatusValue == 3">查看</el-button>
            <el-button size="mini" type="text" @click="reviewClick(scope.row)"
              v-if="scope.row.sellStatusValue == 4">审核</el-button>
            <el-button size="mini" type="text" @click="inventory(scope.row)" v-if="scope.row.sellStatusValue == 2 || scope.row.sellStatusValue == 3">库存配置</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList"></pagination>
    </div>
    <Dialog :id="selectIdList" :pathType="pathType" v-bind="$attrs" v-if="dialogVisible" :visible.sync="dialogVisible"
      @success="_handleSuccess">
    </Dialog>
    <DecreaseDialog :id="selectIdList" v-bind="$attrs" v-if="decreaseVisible" :visible.sync="decreaseVisible"
      @success="_handleSuccess"></DecreaseDialog>
    <LabelDialog :id="selectIdList" v-bind="$attrs" v-if="labelVisible" :visible.sync="labelVisible"
      @success="_handleSuccess"></LabelDialog>
    <!-- 批量上下架 -->
    <DialogUpAndDown :id="upAndDownIdList" :isBatch="isBatch" :listItem="listItem" v-if="upDownVisible" :visible.sync="upDownVisible"
      @success="refreshPage"></DialogUpAndDown>
    <!-- 库存配置 -->
    <InventoryConfiguration :id="selectId" v-if="inventoryConfigVisible" :visible.sync="inventoryConfigVisible"
      @success="refreshPage"></InventoryConfiguration>
    <!-- 图片打包下载 -->
    <ImagePackaging :idList="selectIdList" v-if="imagePackagingVisible" :visible.sync="imagePackagingVisible"
      @success="refreshPage"></ImagePackaging>
  </div>
</template>
  
<script>
import {
  getList,
  editStatus,
  getNum,
  tagSelect
} from "@/api/merchantsNFR/yeCard";
import axios from "axios";

import {
  getToken,
  setStorage,
  getStorage,
  removeStorage
} from "@/utils/auth";
import {
  shopSelect,
} from "@/api/merchantsNFR/castingApplication";
import Dialog from "@/views/merchantsNFR/yeCard/components/dialog";
import DecreaseDialog from "@/views/merchantsNFR/yeCard/components/decreaseDialog";
import LabelDialog from "@/views/merchantsNFR/yeCard/components/labelDialog";
import DialogUpAndDown from "@/views/merchantsNFR/yeCard/components/dialogUpAndDown";
import InventoryConfiguration from "@/views/merchantsNFR/yeCard/components/inventoryConfiguration";
import ImagePackaging from "@/views/merchantsNFR/yeCard/components/imagePackaging";

import ExportExcelButton from "@/components/ExportExcelButton/index";

export default {
  name: "",
  components: {
    Dialog,
    DecreaseDialog,
    LabelDialog,
    ExportExcelButton,
    DialogUpAndDown,
    InventoryConfiguration,
    ImagePackaging
  },
  data() {

    var checkEndPrice = (rule, value, callback) => {
      var startPrice = parseFloat(this.queryParams.startPrice)
      var value = parseFloat(value)
      let regNumber = /(^[1-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/; //大于0的数值且最多保留两位小数的数值
      if (startPrice >= value) {
        return callback(new Error("只能填写大于最低售价的数值"));
      } else {
        return callback();
      }

    };
    return {
      exportLoading: false,
      dialogId: "",
      dialogVisible: false,
      decreaseVisible: false, //增删 弹窗
      labelVisible: false,
      upDownVisible: false,//批量上下架
      inventoryConfigVisible: false,//库存配置
      imagePackagingVisible: false,//图片打包中
      // 遮罩层
      loading: false,
      // 导出遮罩层
      // 总条数
      total: 0,//状态字典数组

      //表格数据
      tabList: [],
      date: [],
      merchantList: [],//所属门店
      statusList: [
        { id: '1', value: '待开始' },
        { id: '2', value: '进行中' },
        { id: '3', value: '已结束' },
      ],
      typeList: [
        { id: '', value: '全部' },
        { id: '2', value: '销售中', num: 0 },
        { id: '3', value: '待上架', num: 0 },
        { id: '1', value: '草稿', num: 0 },
        { id: '4', value: '待审核', num: 0 },
        { id: '5', value: '已拒绝', num: 0 },
      ],
      tagList: [],//标签列表
      functionTypeList: [],
      pathType: "add",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: "", //卡查询
        merchantIdList: [], //店铺商家id集合
        sellStatusList: [],//上架状态
        assistanceStatus: '',//同行助力激励状态 1 开启 2 关闭
        incentiveStatus: '',//消费后激励活动 1 开启 2 关闭
        startPrice: '',//开始价格
        endPrice: '',//结束价格
        exportIdList: [],//	导出id列表
        updateStartTime: '',//修改开始时间
        updateEndTime: '',//修改结束时间
        tagIdList: [],//标签id
        activeList: [],
        date: [],
      },
      currentNavtab: '',
      selectIdList: [], //选择id列表
      upAndDownIdList:[],//上下架选择列表
      selectId: '',//所选id
      listItem:{},//上下架所选item
      isBatch: false,//是否批量上下架
      activeList: [
        { id: 1, value: '消费激励' },
        { id: 2, value: '同行助力' },
      ],
      rules: {
        endPrice: [
          { validator: checkEndPrice, required: true, trigger: ["change"] }
        ],
      }
    };
  },
  computed: {
    ExportIncentive() {
      const params = {
        ...this.incentiveData,
      };
      return params;
    },
    ExportAssistance() {
      const params = {
        ...this.assistanceData,
      };
      return params;
    },
  },
  created() {
    var queryParams = JSON.parse(localStorage.getItem('queryParams'))
    if (queryParams) {
      this.queryParams = queryParams
      if (queryParams.sellStatusList.length == 1) {
        this.currentNavtab = queryParams.sellStatusList[0]
      }
    }
    console.log(2222222222, this.queryParams)
    this.getStatusList()
    this.getMerchant()
    this.getList();
    this.getNum()
    this.getTag()
  },
  methods: {
    //初始化方法
    init() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        name: "", //卡查询
        merchantIdList: [], //店铺商家id集合
        sellStatusList: [],//上架状态
        assistanceStatus: '',//同行助力激励状态 1 开启 2 关闭
        incentiveStatus: '',//消费后激励活动 1 开启 2 关闭
        startPrice: '',//开始价格
        endPrice: '',//结束价格
        exportIdList: [],//	导出id列表
        updateStartTime: '',//修改开始时间
        updateEndTime: '',//修改结束时间
        tagIdList: [],//标签id
        activeList: [],
        date: [],
      }
    },
    getNum() {
      getNum(this.queryParams).then((response) => {
        var data = response.result
        this.typeList[1].num = data.sale
        this.typeList[2].num = data.waitUp
        this.typeList[3].num = data.draft
        this.typeList[4].num = data.waitAudit
        this.typeList[5].num = data.reject
      });
    },
    // 获取活动状态字典
    getStatusList() {
      var dictType = "merchant_equity_card_sell_up_status";
      this.$getSelectList(dictType)
        .then((res) => {
          this.functionTypeList = res.result[0].dictList
        })
        .finally(() => { });
    },
    //获取所属门店下拉
    getMerchant() {
      shopSelect().then(res => {
        this.merchantList = res.result
      })
    },
    //获取标签下拉
    getTag() {
      tagSelect().then(res => {
        this.tagList = res.result
      })
    },
    getTime(e) {
      console.log("e", e)
      this.queryParams.updateStartTime = e[0]
      this.queryParams.updateEndTime = e[1]
    },
    //处理参与活动
    changeActiveList(e) {
      this.queryParams.incentiveStatus = 2
      this.queryParams.assistanceStatus = 2
      console.log('e', e)
      var list = e
      list.forEach(item => {
        if (item == 1) {
          this.queryParams.incentiveStatus = 1
        } else if (item == 2) {
          this.queryParams.assistanceStatus = 1
        }
      })
      console.log('this.queryParams.incentiveStatus', this.queryParams.incentiveStatus)
      console.log('this.queryParams.assistanceStatus', this.queryParams.assistanceStatus)

    },
    handleSelectionChange(val) {
      var selList = []
      val.forEach(item => {
        selList.push(item.id)
      });
      this.selectIdList = selList
      this.queryParams.exportIdList = selList
    },
    //切换选项
    handleTab(id) {
      this.init()

      if (id != '') {
        this.queryParams.sellStatusList = []
        this.queryParams.sellStatusList[0] = id
      } else {
        this.queryParams.sellStatusList = []
      }
      localStorage.setItem('queryParams', JSON.stringify(this.queryParams))
      this.currentNavtab = id;
      this.getList();
      this.getNum()
    },

    /** 查询列表 */
    getList() {
      this.loading = true;
      let data = JSON.parse(JSON.stringify(this.queryParams));  //深拷贝
      delete data.exportIdList
      getList(data).then((response) => {
        response.result.records.forEach(item => {
          for (var key in item) {
            if (item[key] === '') {
              item[key] = "-";
            }
          }
        });
        this.tabList = response.result.records;
        this.tabList = this.tabList.map(item => {
          item.tag = item.tag.split('、')
          return item
        })
        this.total = response.result.total;
        this.loading = false;
      });
    },
    // 表单重置
    reset() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        name: "", //卡查询
        merchantIdList: [], //店铺商家id集合
        sellStatusList: [],//上架状态
        assistanceStatus: '',//同行助力激励状态 1 开启 2 关闭
        incentiveStatus: '',//消费后激励活动 1 开启 2 关闭
        startPrice: '',//开始价格
        endPrice: '',//结束价格
        exportIdList: [],//	导出id列表
        updateStartTime: '',//修改开始时间
        updateEndTime: '',//修改结束时间
        activeList: [],
        date: [],
      };
      this.currentNavtab = ''
      this.resetForm("queryForm");
      this.getList();
      this.getNum()
    },
    /** 搜索按钮操作 */
    handleQuery(formName) {
      //创建确定
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.queryParams.pageNum = 1;
          this.getList();
          this.getNum()
          localStorage.setItem('queryParams', JSON.stringify(this.queryParams))
        } else {
          console.log("error submit!!");
          return false;
        }
      });

    },
    /** 重置按钮操作 */
    resetQuery() {
      // this.resetForm("queryForm");
      this.init()
      localStorage.setItem('queryParams', JSON.stringify(this.queryParams))
      this.reset();
      // this.handleQuery();
    },
    //新增
    addClick() {
      this.$router.push({
        path: "/merchantsNFR/addYeCard",
        query: {
          // id: row.id,
          pathType: 'add',
          permissions: 1,
        },
      })
    },
    //批量配置运营活动
    handleConfig() {
      if (this.selectIdList.length < 1) {
        this.$message.error(`请勾选商品`);
        return false;
      }
      this.dialogVisible = true
    },
    //修改
    reviseClick(row) {
      this.$router.push({
        path: "/merchantsNFR/addYeCard",
        query: {
          pathType: 'revise',
          id: row.id,
          permissions: 1,
        },
      })
    },
    // 编辑
    editClick(row) {
      this.$router.push({
        path: "/merchantsNFR/addYeCard",
        query: {
          pathType: 'edit',
          id: row.id,
          permissions: 1,
        },
      })
    },
    // 查看
    lookClick(row) {
      this.$router.push({
        path: "/merchantsNFR/yeCardDetail",
        query: {
          id: row.id,
          permissions: 1,
        },
      })
    },
    //审核
    reviewClick(row) {
      this.$router.push({
        path: "/merchantsNFR/addYeCard",
        query: {
          pathType: 'review',
          id: row.id,
          permissions: 1,
        },
      })
    },
    // 库存配置
    inventory(item) {
      this.selectId = item.id
      this.inventoryConfigVisible = true
    },
    // 打包下载图片
    downloadImages() {
      if (this.selectIdList.length < 1) {
          this.$message.error(`请勾选商品`);
          return false;
        }
      this.imagePackagingVisible = true
    },
    //批量上下架
    handlesell(isBatch, item) {
      this.isBatch = isBatch
      this.upAndDownIdList = []
      this.listItem = {}
      if(this.isBatch == false){
        console.log('item',item)
        this.upAndDownIdList.push(item.id)
        this.listItem = item
      }else{
        if (this.selectIdList.length < 1) {
          this.$message.error(`请勾选商品`);
          return false;
        }
        this.upAndDownIdList = [
          ...this.selectIdList
        ]
      }
      this.upDownVisible = true
    },
    //增减虚拟销量
    handleDecrease() {
      if (this.selectIdList.length < 1) {
        this.$message.error(`请勾选商品`);
        return false;
      }
      this.decreaseVisible = true
    },
    //批量设置标签
    handleLabel() {
      if (this.selectIdList.length < 1) {
        this.$message.error(`请勾选商品`);
        return false;
      }
      this.labelVisible = true
    },
    handleCommand(e) {
      console.log('e', e)
      if (e == 1) {
        if (this.selectIdList.length < 1) {
          this.$message.error(`请勾选商品`);
          return false;
        }
        this.exportClick()
      } else {
        this.exportClick()
      }
    },
    //导出
    exportClick() {
      this.exportLoading = true;
      const API = process.env.VUE_APP_BASE_API + '/merchant/lucrative/equity/card/list/export';
      axios.post(API, this.queryParams, {
        headers: {
          "X-Access-Token": getToken(),
        },
        responseType: "blob",
      }).then(res => {
        this.handleData(res);
        this.exportLoading = false;
      }).catch(error => {
        this.exportLoading = false;
      })
    },
    handleData(res) {
      const blob = new Blob([res.data]);
      const downloadElement = document.createElement("a");
      const href = window.URL.createObjectURL(blob); // 创建下载的链接
      downloadElement.href = href;
      downloadElement.download = "赚卡列表.xls"; // 下载后文件名
      document.body.appendChild(downloadElement);
      downloadElement.click(); // 点击下载
      document.body.removeChild(downloadElement); // 下载完成移除元素
      window.URL.revokeObjectURL(href); // 释放掉blob对象
    },
    // 刷新页面
    refreshPage(){
      this.getList();
      this.getNum()
    },
    _handleSuccess(e) {
      //成功回调
      this.init()
      this.getList();
      this.getNum()
    },
    jumpJackpot(row) {
      this.$router.push({
        path: "jackpot",
        query: {
          id: row.id,
        },
      });
    },
  },
};
</script>
<style scoped lang="scss">
.head {
  box-shadow: 0px 4px 12px 0px rgb(1 41 99 / 6%);
  background-color: #fff;
  border-radius: 8px;
  padding: 20px 20px 0;
}

.listBox {
  box-shadow: 0px 4px 12px 0px rgb(1 41 99 / 6%);
  background-color: #fff;
  border-radius: 8px;
  padding: 20px 20px;
  margin-top: 10px;
}

.listBox_head {
  padding: 0 0 20px 0;
}

.el-dropdown,
.ml10 {
  margin-left: 10px;
}

.main_top {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  font-size: 14px;
  color: #333;
  background: #fff;
  border-radius: 6px;
  margin-bottom: 10px;

  .lef {
    display: flex;
    justify-content: flex-start;
    border: 1px solid #dfe6ec;

    .list {
      height: 40px;
      text-align: center;
      line-height: 40px;
      width: 140px;
      text-align: center;
      border-right: 1px solid #dfe6ec;
      background: #fff;
    }

    .list:nth-last-child(1) {
      border: none;
    }

    .active {
      background: #1890ff;
      color: #fff;
    }
  }
}

.img_box {
  width: 100px;
  height: 80px;
  border-radius: 4px;
}

.inpNum {
  display: flex;
  justify-content: flex-start;
  align-items: center;

  .gang {
    margin: 0 6px;
  }

  .el-input {
    width: 100px;
  }
}

.tagBox {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  width: 130px;
  /* 设置容器宽度 */
  word-break: break-all;
  /* 允许单词内换行 */

}
</style>
  